package com.overto.gwt.hermes.client;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Simple callback used for HTTP requests. Just repacks exceptions
 * and calls abstract deserialization method if HTTP result is OK.
 */
public abstract class JSONRequestCallback implements RequestCallback {
	
	private static final int HTTP_OK = 200;
	
	private AsyncCallback callback;
	
	public JSONRequestCallback(AsyncCallback callback) {
		this.callback = callback;
	}

	public void onError(Request request, Throwable exception) {
		callback.onFailure(exception);		
	}

	public void onResponseReceived(Request request, Response response) {
		try {
			if (response.getStatusCode() == HTTP_OK) {
				if (callback instanceof DebugAsyncCallback) {
					((DebugAsyncCallback)callback).beforeDeserialize(response.getText());
				}
				callback.onSuccess(deserialize(response.getText()));
			} else {
				callback.onFailure(new JSONHttpException(response.getStatusCode(), 
						response.getStatusText(), response.getText()));
			}
		} catch (Exception e) {
			callback.onFailure(e);
		}
	}

	public abstract Object deserialize(String text);
}
